package com.wangsd.web.shop.service;

import com.alibaba.fastjson.JSON;
import com.gitee.fastmybatis.core.query.Query;
import com.gitee.fastmybatis.core.util.MyBeanUtil;
import com.wangsd.common.basicbean.weight.Pair;
import com.wangsd.common.basicbean.weight.WeightRandom;
import com.wangsd.common.exception.BusinessException;
import com.wangsd.common.utils.DateUtils;
import com.wangsd.web.shop.entity.Activity;
import com.wangsd.web.shop.entity.ActivityMember;
import com.wangsd.web.shop.entity.Coupon;
import com.wangsd.web.shop.entity.Member;
import com.wangsd.web.shop.mapper.ActivityMapper;
import com.wangsd.web.sys.entity.UploadFile;
import com.wangsd.web.sys.service.UploadFileService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class ActivityService {
    @Resource
    private ActivityMapper mapper;
    @Autowired
    private UploadFileService uploadFileService;
    @Autowired
    CouponService couponService;
    @Autowired
    ActivityMemberService activityMemberService;
    @Autowired
    ActivityDetailService activityDetailService;
    @Autowired
    MemberService memberService;

    public Activity checkActivity(Long id) {
        Query query = new Query();
        query.eq("id", id);
        query.lt("begin_time", new Date());
        query.gt("end_time", new Date());
        return mapper.getByQuery(query);
    }

    public Activity selectCodeAndType(String code, Integer type) {
        Query query = new Query();
        query.eq("parent_code", code);
        query.eq("type", type);
        Activity activity = mapper.getByQuery(query);
        return activity;
    }

    public List<Activity> selectPage(Activity queryObj, String loginCode) {
        Query query = new Query();
        if (queryObj.getType() != null) {
            query.eq("t.type", queryObj.getType());
        }

        if (StringUtils.isNotBlank(loginCode)) {
            query.likeRight("t.parent_code", loginCode);
        }

        if (StringUtils.isNotBlank(queryObj.getParentCode())) {
            query.likeRight("t.parent_code", queryObj.getParentCode());
        }
        query.join("join customer t2 on t.parent_code = t2.code");
        List<String> column = Arrays.asList("t.*, t2.name as customerName");
        List<Map<String, Object>> mapList = mapper.listMap(column, query);
        List<Activity> list = MyBeanUtil.mapListToObjList(mapList, Activity.class);
        return list;
    }

    /**
     * 查询活动列表
     *
     * @param code
     * @param type
     * @return
     */
    public Activity selectByParentCode(String code, Integer type) {
        Activity activity = selectCodeAndType(code, type);
        if (activity != null) {
            Date date = new Date();
            if (activity.getBeginTime() != null && DateUtils.dateDiff(date, activity.getBeginTime(), 6) > 0) {
                activity.setDiffName("活动开始剩余");
                activity.setDiffTime(DateUtils.dateDiff(date, activity.getBeginTime(), 6));
            } else if (activity.getEndTime() != null && DateUtils.dateDiff(date, activity.getEndTime(), 6) > 0) {
                activity.setDiffName("活动结束剩余");
                activity.setDiffTime(DateUtils.dateDiff(date, activity.getEndTime(), 6));
            } else {
                activity.setDiffName("活动已结束");
            }
            List<Coupon> couponList;
            if (type == 2) {
                couponList = couponService.selectType2ByActivityId(activity.getId());
            } else {
                couponList = couponService.selectAllByIDs(JSON.parseArray(activity.getCouponIds(), Long.class));
            }
            activity.setCouponList(couponList);
        }
        return activity;
    }

    @Transactional
    public void updateActivity(Activity entity) {
        if (entity.getId() == null) {
            Activity activity = selectCodeAndType(entity.getParentCode(), entity.getType());
            if (activity != null) {
                throw new BusinessException("同一类型的活动只能有一个,请先删除");
            }
            mapper.saveIgnoreNull(entity);
        }
        if (entity.getFilename() != null) {
            UploadFile uploadFile = new UploadFile();
            uploadFile.setMasterId(entity.getId());
            uploadFile.setFilename(entity.getFilename());
            uploadFile.setMasterType(7);
            String fileUrl = uploadFileService.updateUploadFile2(uploadFile);
            entity.setFileUrl(fileUrl);
        }
        if (entity.getDetailList() != null && entity.getDetailList().size() > 0) {
            activityDetailService.save(entity.getId(), entity.getDetailList());
        }
        mapper.updateIgnoreNull(entity);
    }

    @Transactional
    public int deleteById(Long id) {
        Activity activity = mapper.getById(id);
        //删除关联图片
        uploadFileService.deleteByMasterIdAndType(activity.getId(), 7);
        //删除活动领取记录
        activityMemberService.deleteByActivityId(id);
        return mapper.deleteById(id);
    }

    public int saveBatch(List<Activity> list) {
        return mapper.saveBatch(list);
    }

    @Transactional
    public void deleteByCustomerId(String parentCode) {
        Query query = new Query();
        query.eq("parent_code", parentCode);
        List<Activity> list = mapper.list(query);
        for (Activity activity : list) {
            deleteById(activity.getId());
        }
    }

    /**
     * 抽奖
     *
     * @param activityId
     * @param miniOpenid
     */
    @Transactional
    public Coupon luckDraw(Long activityId, String miniOpenid) {
        Activity activity = this.checkActivity(activityId);
        if (activity == null) {
            throw new BusinessException("不在活动时间范围");
        }
        String receiveTime = DateUtils.formatDate(new Date());
        List<ActivityMember> list = activityMemberService.selectByMiniOpenid(miniOpenid, receiveTime);
        if (list.size() >= activity.getOneDayCount()) {
            throw new BusinessException("您今天已经抽过奖了");
        }
        //开始抽奖
        List<Coupon> couponList = couponService.selectLuckDraw(activityId);
        if (couponList.size() <= 0) {
            throw new BusinessException("奖品已抽完");
        }

        //构造数组
        List weightList = new ArrayList<Pair>();
        for (int i = 0; i < couponList.size(); i++) {
            Coupon coupon = couponList.get(i);
            Pair pair = new Pair(i, coupon.getRate());
            weightList.add(pair);
        }
        Pair[] options = new Pair[weightList.size()];
        weightList.toArray(options);
        WeightRandom rnd = new WeightRandom(options);
        int index = (Integer) rnd.nextItem();
        Coupon coupon = couponList.get(index);
        /*平均每个商品的角度*/
        int angleN = 360 / couponList.size();
        /*返回当前商品角度*/
        int angle = index * angleN;
        coupon.setAngle(angle);

        if (coupon.getType() != 4) {
            //发放奖品
            Member member = memberService.selectByMiniOpenId(miniOpenid);
            couponService.sendCoupon(coupon, member, null);
        }
        //保存抽奖记录
        activityMemberService.save(activityId, miniOpenid, receiveTime);
        return coupon;
    }
}
